package com.changgou.oauth.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.oauth.service.AuthService;
import com.changgou.oauth.util.AuthToken;
import com.changgou.oauth.util.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/oauth")
public class AuthController {
    @Autowired
    private AuthService authService;
    //加载客户端id
    @Value("${auth.clientId}")
    private String clientId;
    //加载客户端密钥
    @Value("${auth.clientSecret}")
    private String clientSecret;
    //加载客户端域名
    @Value("${auth.cookieDomain}")
    private String cookieDomain;
    //加载cookie最长时间
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @RequestMapping("/toLogin")
    public String toLogin(@RequestParam(value = "FROM", required = false, defaultValue = "") String from, Model model) {
        model.addAttribute("from", from);
        return "login";
    }

    @RequestMapping("/login")
    @ResponseBody
    public Result login(String username, String password, HttpServletResponse response) {
        //校验参数
        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("请输入用户名");
        }

        if (StringUtils.isEmpty(password)) {
            throw new RuntimeException("请输入密码");
        }

        //申请令牌
        AuthToken authToken = authService.login(username, password, clientId, clientSecret);

        //将Jti的值存入cookie中
        this.saveJitToCookie(authToken.getJti(), response);

        //返回结果
        return new Result(true, StatusCode.OK, "登录成功");
    }

    //将Jti的值存入cookie中
    private void saveJitToCookie(String jti, HttpServletResponse response) {
        /**
         * httpResponse:客户端响应对象
         * cookieDomain：cookie的域
         * path: 携带参数的路径
         * uid: cookie存储的键
         * jtw: cookie存储的值
         * cookieMaxAge： 最长存活时间 -1代表关闭会话后结束
         * httpOnly : false 则表示不限定 仅仅http请求
         */
        CookieUtil.addCookie(response, cookieDomain, "/", "uid", jti, cookieMaxAge, false);
    }
}
